package com.dmzc.linkedlist;

//2.swap-node-in-pairs
//可以使用递归的方式做，可以使用一个哨兵节点来简化head的替换操作
public class SwapNodesInPairs {
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        ListNode tail = head;
        tail = tail.next = new ListNode(2);
        tail = tail.next = new ListNode(3);
        tail = tail.next = new ListNode(4);
        tail = tail.next = new ListNode(5);
        tail = tail.next = new ListNode(6);
        //成对中的第一个数
        ListNode node1 = head;
        //成对中的第二个数
        ListNode node2 = head.next;
        //下一个开始交换的节点
        ListNode tmp = null;
        //上一次处理后的最后节点
        ListNode tmp2 = null;
        while (node1 != null && node2 != null) {
            if (head == node1)
                head = node2;
            tmp = node2.next;
            node2.next = node1;
            node1.next = tmp;
            if (tmp2 != null)
                tmp2.next = node2;
            tmp2 = node1;
            node1 = tmp;
            if (node1 != null)
                node2 = node1.next;
        }
        head.show();
    }
}
